﻿using ServerBase.Config;
using ServerBase.Protocol;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using UtilLib;
using System.Data;
using UtilPublic.Mysql;
using UtilWpf;

namespace ToolGame
{
    /// <summary>
    /// PageRecord.xaml 的交互逻辑
    /// </summary>
    public partial class PageRecord : Page
    {
        public PageRecord()
        {
            InitializeComponent();

            ComboBoxRecPlatform.ComboBox.ItemsSource = Conf.ConfToolServerPlatformExt.Keys;
            ComboBoxRecPlatform.ComboBox.SelectedIndex = 1;

            ComboBoxRecServer.ComboBox.ItemsSource = Conf.ConfToolServerGameExt.Keys;
            ComboBoxRecServer.ComboBox.SelectedIndex = 0;

            ComboBoxRecType.ComboBox.ItemsSource = Enum.GetValues(typeof(ERecordType));
            ComboBoxRecType.ComboBox.SelectedIndex = 2;
            ComboBoxRecSource.ComboBox.ItemsSource = Enum.GetValues(typeof(EActionSource));
            ComboBoxRecSource.ComboBox.SelectedIndex = 1;

            var DtNow = DateTime.Now;
            DateTimePickerRecStart.ValueDateTime = DtNow.Date.AddDays(-9);
            DateTimePickerRecEnd.ValueDateTime = DtNow.Date.AddDays(1);

            MainWindow.绑定控制器(this);
        }

        // 数据库线程数据库连接
        public DbMysql ToolMysql = null;

        public bool DbMysqlConnect(ConfigServerPlatform conf)
        {
            ToolMysql = new DbMysql(conf.MysqlDataSourceRemote
                , conf.MysqlPort
                , conf.MysqlUserId
                , conf.MysqlPassword
                , conf.MysqlDatabase);
            ToolMysql.DbMysqlConnect();
            return DbMysqlIsConnect();
        }
        public bool DbMysqlIsConnect()
        {
            if (ToolMysql == null)
            {
                return false;
            }
            return ToolMysql.IsConnect();
        }
        private void Button_Click_RecDbMysqlConnect(object sender, RoutedEventArgs e)
        {
            EServerPlatform ServerPlatform;
            try
            {
                ServerPlatform = (EServerPlatform)Enum.Parse(typeof(EServerPlatform), ComboBoxRecPlatform.ComboBoxText);
            }
            catch
            {
                App.DebugError("错误的数据库类型！");
                return;
            }
            if (!Conf.ConfToolServerPlatformExt.TryGetValue(ServerPlatform, out var conf))
            {
                App.DebugError("错误的数据库类型！");
                return;
            }
            if (DbMysqlConnect(conf))
            {
                App.DebugInfo("数据库连接成功！");
            }
        }
        private void Button_Click_RecTime(object sender, RoutedEventArgs e)
        {
            var DtNow = DateTime.Now;
            var button = (Button)sender;
            switch (button.Content)
            {
                case "最近一月":
                    DateTimePickerRecStart.ValueDateTime = DtNow.Date.AddDays(-29);
                    DateTimePickerRecEnd.ValueDateTime = DtNow.Date.AddDays(1);
                    break;
                case "最近十天":
                    DateTimePickerRecStart.ValueDateTime = DtNow.Date.AddDays(-9);
                    DateTimePickerRecEnd.ValueDateTime = DtNow.Date.AddDays(1);
                    break;
                case "最近一周":
                    DateTimePickerRecStart.ValueDateTime = DtNow.Date.AddDays(-6);
                    DateTimePickerRecEnd.ValueDateTime = DtNow.Date.AddDays(1);
                    break;
                case "向前一天":
                    DateTimePickerRecStart.ValueDateTime = DateTimePickerRecStart.ValueDateTime.AddDays(-1);
                    DateTimePickerRecEnd.ValueDateTime = DateTimePickerRecEnd.ValueDateTime.AddDays(-1);
                    break;
                case "今天整天":
                    DateTimePickerRecStart.ValueDateTime = DtNow.Date;
                    DateTimePickerRecEnd.ValueDateTime = DtNow.Date.AddDays(1);
                    break;
                default:
                    break;
            }
        }
        private void Button_Click_RecFind(object sender, RoutedEventArgs e)
        {
            if (!DbMysqlIsConnect()) { return; }

            Dictionary<string, object> dataswhere = new Dictionary<string, object>();

            int 查询时间限制 = 90;
            if ((DateTimePickerRecEnd.ValueDateTime - DateTimePickerRecStart.ValueDateTime) > TimeSpan.FromDays(查询时间限制))
            {
                App.DebugError($"时间跨度不能超过{查询时间限制}天！");
                return;
            }

            ERecordType RecType;
            try
            {
                RecType = (ERecordType)Enum.Parse(typeof(ERecordType), ComboBoxRecType.ComboBox.Text);
            }
            catch
            {
                App.DebugError("错误的日志类型！");
                return;
            }
            EActionSource ActionSource;
            try
            {
                ActionSource = (EActionSource)Enum.Parse(typeof(EActionSource), ComboBoxRecSource.ComboBox.Text);
                dataswhere.Add("ActionSource", ActionSource);
            }
            catch
            {
            }

            if (!(string.IsNullOrEmpty(TextboxRecPuid.TextboxText)))
            {
                var Puid = TextboxRecPuid.TextboxText.ToLong();
                dataswhere.Add("Puid", Puid);
            }

            if (!(string.IsNullOrEmpty(TextboxRecArgs.TextboxText)))
            {
                List<List<string>> listText = TextboxRecArgs.TextboxText.ToListListString();
                foreach (var nnn in listText)
                {
                    if (nnn.Count < 2)
                    {
                        continue;
                    }
                    dataswhere.Add(nnn[0].ToString(), nnn[1]);
                }
            }
            var sqlDateTime = $"(RecTime between '{DateTimePickerRecStart.ValueDateTime}' and '{DateTimePickerRecEnd.ValueDateTime}')";

            if (!Conf.ConfToolServerGameExt.TryGetValue(ComboBoxRecServer.ComboBox.Text, out var conf))
            {
                App.DebugError("服务器配置ID错误");
                return;
            }
            var tbl = ToolMysql.RunReadDataTable($"{conf.Id}{MysqlRecord.MysqlRecordTableName}{RecType}", dataswhere, sqlDateTime);
            if (tbl == null)
            {
                App.DebugError("查询错误！请检查查询条件！");
                return;
            }

            TextBoxRecInfo.Text = $"共查询到{tbl.Rows.Count}条数据";

            DataGridRecList.ItemsSource = tbl.DefaultView;

            if (true)
            {
                try
                {
                    var dictsum = new Dictionary<long, C_PuidCount>();
                    foreach (DataRow row in tbl.Rows)
                    {
                        long puid = (long)(row[4]);
                        long count = (long)(row[5]);
                        if (!dictsum.TryGetValue(puid, out var oldcount))
                        {
                            oldcount = new C_PuidCount() { Puid = puid };
                        }
                        oldcount.Amount += 1;
                        oldcount.Count += count;
                        dictsum[puid] = oldcount;
                    }
                    DataGridRecListPuid.BindingListObj(dictsum.Values);
                }
                catch { }
            }
        }
        [GridHeader("统计数据")]
        public partial class C_PuidCount
        {
            [GridHeader("玩家唯一ID")]
            public long Puid = 0;
            [GridHeader("数量")]
            public long Amount = 0;
            [GridHeader("总计")]
            public long Count = 0;
        };

    }
}
